﻿using System.Web.Mvc;
using yiCommerce.Core;
using yiCommerce.Core.Domain.Securitys;
using yiCommerce.Service.Securitys;

namespace yiCommerce.Attributes
{
    public class AdminOrderAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!this.HasAdminAccess(filterContext))
                this.HandleUnauthorizedRequest(filterContext);
        }

        private bool HasAdminAccess(AuthorizationContext filterContext)
        {
            var permissionService = EngineContext.Current.Resolve<IPermissionService>();
            var workContext = EngineContext.Current.Resolve<IWorkContext>();
            bool result = permissionService.Authorize(StandardPermissionProvider.ManageOrders, workContext.CurrentCustomer.Id);
            return result;
        }

        private void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}